#include "vcd-vm-rdp-connect.h"
#include "vcd-vm-connect.h"
#include "vcd-get-vm-info.h"
#include "vcd-conf/vcd-conf.h"
#include "vcd-json-parser.h"
#include "vcd-common.h"
#include "vcd-linux-ui/vcd-logined-window.h"
#include "vcd-util.h"
#include "vcd-json-parser.h"
#include "vcd-download.h"
#include "spicy.h"
#include "vcd-linux-ui/vcd-message-dialog.h"
#include "vcd-get-login-ticket.h"

static gboolean connect_windows_system(gpointer data);
static void connect_rdp_callback(void);
static gboolean start_connect_rdp_task(gchar* p);
static int get_guest_ip(void);
static gboolean get_guest_ip_func(gpointer data);

GThread *g_thrdp = NULL;

void stop_rdp_thread(void)
{
    if (g_thrdp) {
        system("killall -9 xfreerdp");
        M_DEBUG("killall -9 xfreerdp");
        g_thread_join(g_thrdp);
        g_thrdp = NULL;
    }
}

static gboolean get_guest_ip_func(gpointer data)
{
    g_return_val_if_fail(data != NULL, FALSE);
    gchar * guest_ip = NULL;
    network_response *res = (network_response*)data;
    if (res->memory == NULL) {
        delete_g_connect_label_and_spinner();
        message_box("   guest-ip获取失败！   ");
        goto end;
    }

    guest_ip = (gchar*)g_malloc0(sizeof(gchar) * 60);
    if(guest_ip == NULL){
        delete_g_connect_label_and_spinner();
        goto end;
    }
    if (json_parser_get_rdp_guest_ip(res->memory, guest_ip) != 0) {
        M_DEBUG("json_parser_get_rdp_guest_ip error");
        delete_g_connect_label_and_spinner();
        message_box("   guest-ip获取失败！   ");
        G_SAFE_FREE(guest_ip);
        goto end;
    }

    M_DEBUG("guest-ip = %s", guest_ip);

    if (strlen(guest_ip) != 0) {
        if (!start_connect_rdp_task(guest_ip)){
            G_SAFE_FREE(guest_ip);
            message_box("创建rdp执行线程失败!");//rdp连接线程创建失败，结束连接，释放资源
        }else{
            goto end;//如果rdp连接线程成功打开！则只释放资源并不结束连接，主界面显示正在连接
        }
    } else {
        G_SAFE_FREE(guest_ip);
        message_box("获取不到桌面IP！请检查是否完成开机!");//接口能返回但是ip为空，有可能是虚拟机未开机，结束连接释放资源
    }

    delete_g_connect_label_and_spinner();

end:
    network_response_free(&res);
    return FALSE;
}

static int get_guest_ip(void)
{
    char url[256] = {0};
    struct curl_slist *list = NULL;
    
    list = curl_slist_append(list, g_token);
    list = curl_slist_append(list, g_final_ticket);

    snprintf(url,sizeof(url),"https://%s/api2/json/nodes/%s/qemu/%d/agent/network-get-interfaces",
             get_ip_port(), connect_data.node, connect_data.vmid);
    //    char guest_ip_post_fields[40] = "command=network-get-interfaces";

    network_request_arg *req = (network_request_arg*)malloc(sizeof(network_request_arg));
    g_return_val_if_fail(req != NULL, -1);

    strncpy(req->url, url, sizeof(req->url));
    req->http_method = CURLOPT_HTTPGET;
    memset(req->post_fields, 0, sizeof(req->post_fields));
    req->timeout = 3;
    req->list = list;
    req->data_priv = NULL;
    req->callback = get_guest_ip_func;
    net_req_list_add(req);
    return 0;
}

//创建线程执行rdp连接过程
static gboolean connect_windows_system(gpointer data)
{
    char cmd[500] = {0};
    gchar* guest_ip = (gchar*)data;
    int res = 0;
    sprintf(cmd, "xfreerdp /v:%s /rfx /f /u:administrator "
                 "/sound:sys:pulse,latency:50,quality:high,format:1 "
                 "/microphone:sys:alsa /disp +fonts "
                 "/cert-ignore +async-update -toggle-fullscreen -sec-nla -compression -bitmap-cache "
                 "/jpeg /menu-anims", guest_ip);
    G_SAFE_FREE(guest_ip);
    res = system(cmd);
    M_DEBUG("rdp connect cmd:%s\nsystem ret:%d", cmd, res);
    //system会阻塞住整个线程(不管xfreerdp是否执行成功)，如果exit_logined_window里面kill xfreerdp之后system会直接返回0
    if (res == 33536 || res == 8192 || res == 2) {
        //33536:虚拟机开启了防火墙  8192:待测
        gdk_threads_add_idle((GSourceFunc)message_box, (gpointer)"虚拟机配置有误，RDP连接失败!");
        M_DEBUG(" 虚拟机配置有误，RDP连接失败！ ");
    }

    connect_rdp_callback();
    return FALSE;
}

//回调结束主界面正在连接标志
static void connect_rdp_callback(void)
{
    M_DEBUG("rdp callback delete connecting flag");
    gdk_threads_add_idle((GSourceFunc)delete_g_connect_label_and_spinner, NULL);
}

//如果rdp连接线程成功打开！则只释放资源并不结束连接，主界面显示正在连接
static gboolean start_connect_rdp_task(gchar* ip)
{
    g_thrdp = g_thread_new("rdp_conn_task", (GThreadFunc)connect_windows_system, (gpointer)ip);
    if (g_thrdp == NULL)
        return FALSE;
    return TRUE;
}

gboolean button_enter_rdp_callback_task(gpointer data)
{
    M_DEBUG("button_enter_rdp_callback_task");
    struct network_response *res = (struct network_response *)data;

    char *memory = res->memory;
    char sys_type[256] = {0};
    int ret = json_parser_get_rdp_guest_system_type(memory, sys_type);
    if (ret != 0) {
        message_box(" 获取不到虚拟机系统类型! ");
        goto end;//释放资源
    }

    M_DEBUG("rdp sys_type = %s", sys_type);

    if (strcmp(sys_type, "win7") != 0 && strcmp(sys_type, "win8") != 0) {
        message_box(" 虚拟机操作系统不支持rdp协议! ");
        goto end;
    }

    if (get_guest_ip() != 0) {
        message_box("   guest-ip获取失败！   ");
        delete_g_connect_label_and_spinner();//获取不到虚拟机ip，结束连接，释放资源
        goto end;
    }
    
    network_response_free(&res);
    return FALSE;

end:
    delete_g_connect_label_and_spinner();
    network_response_free(&res);
    return FALSE;
}

gboolean vcd_vm_rdp_connect_get_guest_ip(FUNC_GUEST_IP func,gpointer priv){
    char url[256] = {0};
    struct curl_slist *list = NULL;
    
    list = curl_slist_append(list, g_token);
    list = curl_slist_append(list, g_final_ticket);

    snprintf(url,sizeof(url),"https://%s/api2/json/nodes/%s/qemu/%d/agent/network-get-interfaces",
             get_ip_port(), connect_data.node, connect_data.vmid);

    network_request_arg *req = (network_request_arg*)malloc(sizeof(network_request_arg));
    g_return_val_if_fail(req != NULL, FALSE);

    strncpy(req->url, url, sizeof(req->url));
    req->http_method = CURLOPT_HTTPGET;
    memset(req->post_fields, 0, sizeof(req->post_fields));
    req->timeout = 3;
    req->list = list;
    req->data_priv = priv;
    req->callback = func;
    net_req_list_add(req);
    return TRUE;
}

gboolean vcd_vm_rdp_connect_get_guest_ip_ext(const char* host,const char* node,int vmid,FUNC_GUEST_IP func,gpointer priv){
    if(!host || !node || vmid < 0 || !func)
        return FALSE;

    //M_DEBUG("vcd_vm_rdp_connect_get_guest_ip_ext host:%s,node:%s,vmid:%d",host,node,vmid);
    char url[256] = {0};
    struct curl_slist *list = NULL;
    
    list = curl_slist_append(list, g_token);
    list = curl_slist_append(list, g_final_ticket);

    snprintf(url,sizeof(url),"https://%s/api2/json/nodes/%s/qemu/%d/agent/network-get-interfaces",
             host, node, vmid);

    network_request_arg *req = (network_request_arg*)malloc(sizeof(network_request_arg));
    g_return_val_if_fail(req != NULL, FALSE);

    strncpy(req->url, url, sizeof(req->url));
    req->http_method = CURLOPT_HTTPGET;
    memset(req->post_fields, 0, sizeof(req->post_fields));
    req->timeout = 3;
    req->list = list;
    req->data_priv = priv;
    req->callback = func;
    net_req_list_add(req);
    return TRUE;
}
